#!/bin/bash
MYSQL_INSTALL_DIR="/usr/local/mysql56" 
MYSQL_CNF="${MYSQL_INSTALL_DIR}/my.cnf"
MYSQL_SERVER_NAME="mysqld"
# 检查是否是root用户
if [ $(id -u) != "0" ]; then
    echo "must root"
    exit 1
fi

echo "+-------------------------------------------------------------------+"
echo "|   Reset MySQL Root Password"
echo "+-------------------------------------------------------------------+"

if [ -s "${MYSQL_INSTALL_DIR}/bin/mysql" ]; then
    DB_Name="mysql"
    DB_Version=$($MYSQL_INSTALL_DIR/bin/mysql_config --version)
else
    echo "MySQL not found!"
    exit 1
fi

while :; do
    DB_Root_Password=""
    read -p "Enter New ${DB_Name} root password: " DB_Root_Password
    if [ "${DB_Root_Password}" = "" ]; then
        echo "Error: Password can't be NULL!!"
    else
        break
    fi
done

echo "Stoping ${DB_Name}..."
if command -v killall >/dev/null 2>&1; then
    killall mysqld
else
    kill $(pidof mysqld)
fi

echo "modify ${MYSQL_CNF} with skip-grant-tables"
sed -i '/\[mysqld\]/askip-grant-tables' $MYSQL_CNF
sleep 2

echo "update ${DB_Name} root password..."
service ${MYSQL_SERVER_NAME} start
if echo "${DB_Version}" | grep -Eqi '^8.0.|^5.7.|^10.[234].'; then
    ${MYSQL_INSTALL_DIR}/bin/mysql -uroot mysql <<EOF
use mysql;
update user set authentication_string = Password('${DB_Root_Password}') where User = 'root';
commit;
flush privileges;
EOF
else
    ${MYSQL_INSTALL_DIR}/bin/mysql -uroot mysql <<EOF
use mysql;
update user set password = Password('${DB_Root_Password}') where User = 'root';
commit;
FLUSH PRIVILEGES;
EOF
fi

if [ $? -eq 0 ]; then
    echo "Password reset succesfully. Now killing mysqld softly"
    sed -i '/skip-grant-tables/d' $MYSQL_CNF
    if command -v killall >/dev/null 2>&1; then
        killall mysqld
    else
        kill $(pidof mysqld)
    fi
    sleep 5
    echo "Restarting the actual ${DB_Name} service"
    service ${MYSQL_SERVER_NAME} start
    echo "Password successfully reset to '${DB_Root_Password}'"
else
    echo "Reset ${DB_Name} root password failed!"
fi
